<?php
class NhdHumanResourcesController extends AppController {

	var $name = 'NhdHumanResources';
	
	public function beforeFilter() {
            parent::beforeFilter();
            //$this->Auth->allow('index');
        }
	
	function index()
	{
		Controller::loadModel('City');
		Controller::loadModel('User');
		
		$city_id = $this->Session->read("c_city_id");
		$year = $this->Session->read("c_year");
		$quarter = $this->Session->read("c_quarter");
		
		$this->layout = 'home';
		
		//Listing branches
		$branches = $this->NhdHumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name'),
									'conditions' => array(
												'Branch.city_id'=>$city_id
											),
								));
		//Listing Employees
		$employees = $this->NhdHumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd'=>1)
									
								));		
		
		//check if have value yet
		$notEmpty = $this->NhdHumanResource->find("count", array(
											'conditions' => array(
												'NhdHumanResource.year' => $year,
												'NhdHumanResource.quarter' => $quarter
											)
										));
		//echo $notEmpty;
		
		//create values array for rendering view
		$bs_rhm = 0;
		foreach($employees as $e => $employee)
		{
			$employees[$e]["total"] = 0;
			foreach($branches as $b => $branch)
			{
				$NhdHumanResource = $this->NhdHumanResource->find("first", array(
											'conditions' => array(
												'NhdHumanResource.branch_id' => $branch["Branch"]["id"],
												'NhdHumanResource.employee_id' => $employee["Employee"]["id"],
												'NhdHumanResource.year' => $year,
												'NhdHumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $NhdHumanResource["NhdHumanResource"]["value"];
				//sum employee
				if($NhdHumanResource["NhdHumanResource"]["value"] != '')
					$employees[$e]["total"] = $employees[$e]["total"] + $NhdHumanResource["NhdHumanResource"]["value"];
					
				//BS RHM
				if(in_array($employee['Employee']['id'], array(10,11)) && $NhdHumanResource["NhdHumanResource"]["value"] != '')
				{
					$bs_rhm += $NhdHumanResource["NhdHumanResource"]["value"];
				}
			}
		}
		
		//echo $bs_rhm;
		$popDocs = $this->getDoctorPopulation($city_id, $year, $quarter);
		$doctor_student = $popDocs['doctors_nhd'] ? round($popDocs['students']/$popDocs['doctors_nhd'],0) :0;
		$nondoctor_student = $popDocs['nondoctors_nhd'] ? round($popDocs['students']/$popDocs['nondoctors_nhd'],0) :0;
		
		$tick_a = array();
		$value_a = array();
		foreach($employees as $e => $employee)
		{
			$value_a[] = $employee["total"];
			$tick_a[] = $employee["Employee"]["name"];
		}
		$value_s = '['.implode(',', $value_a).']';
		$tick_s = '["'.implode('","', $tick_a).'"]';
		
		$this->set(compact('branches', 'employees', 'values', 'tick_s', 'value_s', 'doctor_student', 'nondoctor_student', 'notEmpty'));
	}
	
	function getDoctorPopulation($city_id, $year, $quarter)
	{
		Controller::loadModel('HumanResource');
		Controller::loadModel('CityDetail');
		Controller::loadModel('NhdActivityRecord');
		
		$cities = $this->HumanResource->City->find('all', array(
								'fields'=>array('City.id'),
								'contain'=>false,
								'conditions'=>array(									
									'City.id'=>$city_id
								)
							));
		//var_dump($cities);
		$city_array = $city_id;
		
		//var_dump($city_array);
		
		$employee_array = array(1,2);
		$doctors = $this->HumanResource->find('all', array(
						      'fields'=>array('SUM(HumanResource.value) AS doctors'),
						      'conditions'=>array(
								'HumanResource.employee_id'=>$employee_array,
								'HumanResource.city_id'=>$city_array,
								'HumanResource.year'=>$year,
								'HumanResource.quarter'=>$quarter
						      )
						));
		
		
		//dan so tinh khu vuc
		$population = $this->CityDetail->find('all', array(
								'fields'=>array('SUM(CityDetail.population) AS population'),
								'conditions'=>array(									  
									  'CityDetail.city_id'=>$city_array,
									  'CityDetail.year'=>$year
								)
							));

		//so hoc sinh
		$nd1_a = array(1,2);
		$students = $this->NhdActivityRecord->find('all', array(
								'fields'=>array('SUM(NhdActivityRecord.student_num) AS student_num'),
								'conditions'=>array(									  
									  'NhdActivityRecord.city_id'=>$city_array,
									  'NhdActivityRecord.nhd_activity_id'=>$nd1_a,
									  'NhdActivityRecord.year'=>$year,
									  'NhdActivityRecord.quarter'=>$quarter
								)
							));
		
		//BS RHM NHD
		$employee_nhd_array = array(10,11);
		$doctors_nhd = $this->NhdHumanResource->find('all', array(
						      'fields'=>array('SUM(NhdHumanResource.value) AS doctors'),
						      'conditions'=>array(
								'NhdHumanResource.employee_id'=>$employee_nhd_array,
								'NhdHumanResource.city_id'=>$city_array,
								'NhdHumanResource.year'=>$year,
								'NhdHumanResource.quarter'=>$quarter
						      )
						));
		//BS RHM NHD
		$employee_nhd_array = array(12,13,14,15);
		$nondoctors_nhd = $this->NhdHumanResource->find('all', array(
						      'fields'=>array('SUM(NhdHumanResource.value) AS doctors'),
						      'conditions'=>array(
								'NhdHumanResource.employee_id'=>$employee_nhd_array,
								'NhdHumanResource.city_id'=>$city_array,
								'NhdHumanResource.year'=>$year,
								'NhdHumanResource.quarter'=>$quarter
						      )
						));
		
		return array('population'=>$population[0][0]["population"], 'doctors'=>$doctors[0][0]["doctors"], 'students'=>$students[0][0]["student_num"], 'doctors_nhd'=>$doctors_nhd[0][0]["doctors"], 'nondoctors_nhd'=>$nondoctors_nhd[0][0]["doctors"]);
	}

	function manager_index() {
		$this->NhdHumanResource->recursive = 0;

		Controller::loadModel('Branch');
		
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		//get cities list
		Controller::loadModel('City');
		$user = $this->Auth->user();
		$cities = $this->City->citiesByUser($user["User"]["id"]);
		//var_dump($cities);
		$conditions = array();
		
		//filter city id
		$city_id = !empty($this->params['form']['filter_city_id']) && $this->params['form']['filter_city_id'] != "" ? $this->params['form']['filter_city_id'] : $cities[0]["City"]["id"];
		if($city_id)
		{
			$conditions["Branch.city_id"] = $city_id;
		}
		
		//filter branch
		$branches = $this->Branch->find("all", array('conditions' => array('Branch.city_id'=>$city_id)));
		$branch_id = !empty($this->params['form']['filter_branch_id']) && $this->params['form']['filter_branch_id'] != "" ? $this->params['form']['filter_branch_id'] : 0;
		if($branch_id)
		{
			$conditions["Branch.id"] = $branch_id;
		}
		
		//filter year
		$year = !empty($this->params['form']['filter_year']) && $this->params['form']['filter_year'] != "" ? $this->params['form']['filter_year'] : $c_year;
		if($year)
		{
			$conditions["NhdHumanResource.year"] = $year;
		}
		
		//filter year
		$quarter = !empty($this->params['form']['filter_quarter']) && $this->params['form']['filter_quarter'] != "" ? $this->params['form']['filter_quarter'] : $c_quarter;
		if($quarter)
		{
			$conditions["NhdHumanResource.quarter"] = $quarter;
		}
		
		
		//var_dump($this->params);
		if(count($conditions))
		{
			$this->paginate = array(
				'conditions' => $conditions				
			);
		}
		
		
		$this->set('cities', $cities);
		$this->set('branches', $branches);
		$this->set('city_id', $city_id);
		$this->set('branch_id', $branch_id);
		$this->set('year', $year);
		$this->set('quarter', $quarter);
		
		$this->set('NhdHumanResources', $this->paginate());
	}

	function manager_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid nhd human resource', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('nhdHumanResource', $this->NhdHumanResource->read(null, $id));
	}
	
	function admin_add() {
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		Controller::loadModel('City');
		Controller::loadModel('User');
		$users = $this->NhdHumanResource->User->find('list');
		//$city = $this->City->find("first");
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		
		//Check if user have role on city
		$user = $this->Auth->user();
		$user = $this->NhdHumanResource->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));		
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["NhdHumanResource"]["city_id"]))
		{
			$city = $this->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["NhdHumanResource"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		
		//Listing branches
		$branches = $this->NhdHumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name', 'Branch.city_id'),
									'conditions' => array(
												'Branch.city_id'=>$city["id"]
											),
								));
		//Listing Employees
		$employees = $this->NhdHumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd'=>1)
									
								));		
		
		$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		//$year = date('Y');
		//$quarter = date('m')%3 + 1;
		
		$user = $this->Auth->user();
		
		//echo $user["User"]["id"];
		
		
		//check if the user has accessibility to city					
		if(!$this->User->isUserCity($user["User"]["id"], $city["id"]))
		{
			$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
			$this->redirect(array('action' => 'index'));
		}
			
			
		
		if (!empty($this->data)) {			
			//Saving NhdHumanResource values
			foreach($branches as $b => $branch)
			{
				foreach($employees as $e => $employee)
				{
					$value = $this->data["values"][$branch["Branch"]["id"]][$employee["Employee"]["id"]];
					
					//Convert to good-looking number
					$value = str_replace(",", "", $value);
					
					//check if record exsits
					$exsit = $this->NhdHumanResource->find("first", array(
											'conditions' => array(
												'NhdHumanResource.branch_id' => $branch["Branch"]["id"],
												'NhdHumanResource.Employee_id' => $employee["Employee"]["id"],
												'NhdHumanResource.year' => $this->data["NhdHumanResource"]["year"],
												'NhdHumanResource.quarter' => $this->data["NhdHumanResource"]["quarter"]
											)
										));
						
					//echo $exsit["NhdHumanResource"]["id"];
					$NhdHumanResource = $this->data;
					$NhdHumanResource["NhdHumanResource"]["value"] = $value;
					$humanresource["NhdHumanResource"]["city_id"] = $branch["Branch"]["city_id"];
					$NhdHumanResource["NhdHumanResource"]["branch_id"] = $branch["Branch"]["id"];
					$NhdHumanResource["NhdHumanResource"]["employee_id"] = $employee["Employee"]["id"];
					$NhdHumanResource["NhdHumanResource"]["user_id"] = $user["User"]["id"];
					
					//echo $NhdHumanResource["NhdHumanResource"]["value"];					
						
					
					if(empty($exsit["NhdHumanResource"]["id"]))
					{
						if($value != "") //if there first record, create record and store the value
						{						
							$this->NhdHumanResource->create();
							if ($this->NhdHumanResource->save($NhdHumanResource)) {
							$this->Session->setFlash(__('Thông tin đã được lưu', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
							} else {
								$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
							}
						}					
					}
					else //if record exsits, change its value
					{
						$NhdHumanResource["NhdHumanResource"]["id"] = $exsit["NhdHumanResource"]["id"];
						//echo $value."o";
						if ($this->NhdHumanResource->save($NhdHumanResource)) {
							$this->Session->setFlash(__('Thông tin đã được lưu', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
						} else {
							$this->Session->setFlash(__('The Employee resource could not be saved. Please, try again.', true));
						}
					}					
				}
			}
			$year = $this->data["NhdHumanResource"]["year"];
			$quarter = $this->data["NhdHumanResource"]["quarter"];
		}
		
		//create values array for rendering view
		foreach($branches as $b => $branch)
		{
			foreach($employees as $e => $employee)
			{
				$NhdHumanResource = $this->NhdHumanResource->find("first", array(
											'conditions' => array(
												'NhdHumanResource.branch_id' => $branch["Branch"]["id"],
												'NhdHumanResource.Employee_id' => $employee["Employee"]["id"],
												'NhdHumanResource.year' => $year,
												'NhdHumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $NhdHumanResource["NhdHumanResource"]["value"];
			}
		}
		
		//listing unit
		$units = $this->NhdHumanResource->Unit->find('list');
		$this->data["NhdHumanResource"]["unit_id"] = !empty($this->data["NhdHumanResource"]["unit_id"])?$this->data["NhdHumanResource"]["unit_id"]:1;
		
		$this->set(compact('users', 'cities', 'branches', 'employees', 'values', 'year', 'quarter', 'city', 'units'));
	}

	function manager_add() {
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		Controller::loadModel('City');
		Controller::loadModel('User');
		$users = $this->NhdHumanResource->User->find('list');
		//$city = $this->City->find("first");
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		
		//Check if user have role on city
		$user = $this->Auth->user();
		$user = $this->NhdHumanResource->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));		
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["NhdHumanResource"]["city_id"]))
		{
			$city = $this->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["NhdHumanResource"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		
		//Listing branches
		$branches = $this->NhdHumanResource->Branch->find('all',array(								  
									'fields' => array('Branch.id', 'Branch.name', 'Branch.city_id'),
									'conditions' => array(
												'Branch.city_id'=>$city["id"]
											),
								));
		//Listing Employees
		$employees = $this->NhdHumanResource->Employee->find('all',array(
								  
									'fields' => array('Employee.id', 'Employee.name'),
									'conditions'=>array('Employee.nhd'=>1)
									
								));		
		
		//$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		//$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		$year = date('Y');
		$quarter = round(date('m')/3,0);
		
		$user = $this->Auth->user();
		
		//echo $user["User"]["id"];
		
		
		//check if the user has accessibility to city					
		if(!$this->User->isUserCity($user["User"]["id"], $city["id"]))
		{
			$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
			$this->redirect(array('action' => 'index'));
		}
			
			
		
		if (!empty($this->data)) {			
			//Saving NhdHumanResource values
			foreach($branches as $b => $branch)
			{
				foreach($employees as $e => $employee)
				{
					$value = $this->data["values"][$branch["Branch"]["id"]][$employee["Employee"]["id"]];
					
					//Convert to good-looking number
					$value = str_replace(",", "", $value);
					
					//check if record exsits
					$exsit = $this->NhdHumanResource->find("first", array(
											'conditions' => array(
												'NhdHumanResource.branch_id' => $branch["Branch"]["id"],
												'NhdHumanResource.Employee_id' => $employee["Employee"]["id"],
												'NhdHumanResource.year' => $this->data["NhdHumanResource"]["year"],
												'NhdHumanResource.quarter' => $this->data["NhdHumanResource"]["quarter"]
											)
										));
						
					//echo $exsit["NhdHumanResource"]["id"];
					$NhdHumanResource = $this->data;
					$NhdHumanResource["NhdHumanResource"]["value"] = $value;
					$humanresource["NhdHumanResource"]["city_id"] = $branch["Branch"]["city_id"];
					$NhdHumanResource["NhdHumanResource"]["branch_id"] = $branch["Branch"]["id"];
					$NhdHumanResource["NhdHumanResource"]["employee_id"] = $employee["Employee"]["id"];
					$NhdHumanResource["NhdHumanResource"]["user_id"] = $user["User"]["id"];
					
					//echo $NhdHumanResource["NhdHumanResource"]["value"];					
						
					
					if(empty($exsit["NhdHumanResource"]["id"]))
					{
						if($value != "") //if there first record, create record and store the value
						{						
							$this->NhdHumanResource->create();
							if ($this->NhdHumanResource->save($NhdHumanResource)) {
							$this->Session->setFlash(__('Thông tin đã được lưu', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
							} else {
								$this->Session->setFlash(__('The human resource could not be saved. Please, try again.', true));
							}
						}					
					}
					else //if record exsits, change its value
					{
						$NhdHumanResource["NhdHumanResource"]["id"] = $exsit["NhdHumanResource"]["id"];
						//echo $value."o";
						if ($this->NhdHumanResource->save($NhdHumanResource)) {
							$this->Session->setFlash(__('Thông tin đã được lưu', true));
							//$this->redirect(array('action' => 'index'));							
							//break;
						} else {
							$this->Session->setFlash(__('The Employee resource could not be saved. Please, try again.', true));
						}
					}					
				}
			}
			$year = $this->data["NhdHumanResource"]["year"];
			$quarter = $this->data["NhdHumanResource"]["quarter"];
		}
		
		//create values array for rendering view
		foreach($branches as $b => $branch)
		{
			foreach($employees as $e => $employee)
			{
				$NhdHumanResource = $this->NhdHumanResource->find("first", array(
											'conditions' => array(
												'NhdHumanResource.branch_id' => $branch["Branch"]["id"],
												'NhdHumanResource.Employee_id' => $employee["Employee"]["id"],
												'NhdHumanResource.year' => $year,
												'NhdHumanResource.quarter' => $quarter
											)
										));
				$values[$branch["Branch"]["id"]][$employee["Employee"]["id"]] = $NhdHumanResource["NhdHumanResource"]["value"];
			}
		}
		
		//listing unit
		$units = $this->NhdHumanResource->Unit->find('list');
		$this->data["NhdHumanResource"]["unit_id"] = !empty($this->data["NhdHumanResource"]["unit_id"])?$this->data["NhdHumanResource"]["unit_id"]:1;
		
		$this->set(compact('users', 'cities', 'branches', 'employees', 'values', 'year', 'quarter', 'city', 'units'));
	}

	function manager_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid nhd human resource', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			
			//check if the user has accessibility to city
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["NhdHumanResource"]["branch_id"]);
			Controller::loadModel('User');
			if(!$this->User->isUserCity($user["User"]["id"], $branch["Branch"]["city_id"]))
			{
				$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
				$this->redirect(array('action' => 'index'));
			}
			
			if ($this->NhdHumanResource->save($this->data)) {
				$this->Session->setFlash(__('The nhd human resource has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The nhd human resource could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->NhdHumanResource->read(null, $id);
			$year = $this->data["NhdHumanResource"]["year"];
			
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["NhdHumanResource"]["branch_id"]);
		}
		$users = $this->NhdHumanResource->User->find('list');
		$branches = $this->NhdHumanResource->Branch->find('list', array('conditions'=>array('Branch.city_id'=>$branch["Branch"]["city_id"])));
		$employees = $this->NhdHumanResource->Employee->find('list');
		$units = $this->NhdHumanResource->Unit->find('list');
		$this->set(compact('users', 'branches', 'employees', 'units', 'year'));
	}

	function manager_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for nhd human resource', true));
			$this->redirect(array('action'=>'index'));
		}
		
		//check if user has role on city
			$this->data = $this->NhdHumanResource->read(null, $id);
			//check if the user has accessibility to city
			Controller::loadModel('Branch');
			$user = $this->Auth->user();
			$branch = $this->Branch->read(null, $this->data["NhdHumanResource"]["branch_id"]);
			Controller::loadModel('User');
			if(!$this->User->isUserCity($user["User"]["id"], $branch["Branch"]["city_id"]))
			{
				$this->Session->setFlash(__('Manager doesn\'t has role on this city', true));
				$this->redirect(array('action' => 'index'));
			}
		
		if ($this->NhdHumanResource->delete($id)) {
			$this->Session->setFlash(__('Nhd human resource deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Nhd human resource was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
